package com.ruoyi.common.tools.excel.base;

import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.ruoyi.common.excel.ExcelListener;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.StreamUtils;

import cn.hutool.core.util.StrUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class MyExcelListener<T> extends AnalysisEventListener<T> implements ExcelListener<T> {

    /**
     * excel 表头数据
     */
    protected Map<Integer, String> headMap;
    
    protected Integer getHeadColIndex(String headName) {
    	for (Map.Entry<Integer, String> m : this.headMap.entrySet()) {
    		if (m.getValue().equals(headName)) {
    			return m.getKey();
    		}
    	}
    	return null;
    }
    
    /**
     * map<row , map<col , ossId>>
     */
    @Setter
    protected Map<Integer , Map<Integer , String>> excelPicMap;
    
    protected int row = 0;
    
    /**
     * 导入回执
     */
    protected MyExcelResult<T> excelResult;

    public MyExcelListener() {
        this.excelResult = new MyExcelResult<>();
    }

    protected String getPicOssIdOnMap(Integer row , Integer col) {
		if (null != this.excelPicMap) {
			Map<Integer , String> colMap = this.excelPicMap.get(row);
			if (null != colMap) {
				return colMap.get(col);
			}
		}
		
		return null;
	}
    
    /**
     * 处理异常
     *
     * @param exception ExcelDataConvertException
     * @param context   Excel 上下文
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        String errMsg = null;
        if (exception instanceof ExcelDataConvertException) {
            // 如果是某一个单元格的转换异常 能获取到具体行号
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            Integer rowIndex = excelDataConvertException.getRowIndex();
            Integer columnIndex = excelDataConvertException.getColumnIndex();
            errMsg = StrUtil.format("第{}行-第{}列-表头{}: 解析异常<br/>",
                rowIndex + 1, columnIndex + 1, headMap.get(columnIndex));
            if (log.isDebugEnabled()) {
                log.error(errMsg);
            }
        }
        if (exception instanceof ConstraintViolationException) {
            ConstraintViolationException constraintViolationException = (ConstraintViolationException) exception;
            Set<ConstraintViolation<?>> constraintViolations = constraintViolationException.getConstraintViolations();
            String constraintViolationsMsg = StreamUtils.join(constraintViolations, ConstraintViolation::getMessage, ", ");
            errMsg = StrUtil.format("第{}行数据校验异常: {}", context.readRowHolder().getRowIndex() + 1, constraintViolationsMsg);
            if (log.isDebugEnabled()) {
                log.error(errMsg);
            }
        }
        excelResult.getErrorList().add(errMsg);
        //throw new ExcelAnalysisException(errMsg);
        this.doOnExceptionProcess(errMsg);
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        this.headMap = headMap;
        this.row++;
        log.debug("解析到一条表头数据: {}", JsonUtils.toJsonString(headMap));
    }

    @Override
    public void invoke(T data, AnalysisContext context) {
    	excelResult.getList().add(data);
    	this.doValidate(data, context);
    	this.row++;
    }
    
    /**
     * 解析excel异常时处理
     * @param errorMsg
     */
    protected abstract void doOnExceptionProcess(String errorMsg);
    
    /**
     * 导入参数校验
     * @param data 导入数据对象
     * @param context excel 上下文
     */
    protected abstract void doValidate(T data, AnalysisContext context); 
    
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.debug("所有数据解析完成！");
    }

    @Override
    public MyExcelResult<T> getExcelResult() {
        return excelResult;
    }

}
